package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import tools.DateTools;

public class CSV_Handler {

	String mySplitter;
	String data_records;
	String CSV_FilePath;
	String outputDevice;
	final String CSVFile = "CSV";

	public CSV_Handler(String baseFP, String name, String fieldSplitter, String output) {
		data_records = "";
		mySplitter = fieldSplitter;
		outputDevice = output;
		DateTools ts = new DateTools();
		File csvFP = new File(baseFP + name + "-" + ts.getDateTime() + ".csv");
		CSV_FilePath = csvFP.getPath();
	}

	public CSV_Handler(String splitter, String csv_path) {
		data_records = "";
		mySplitter = splitter;
		CSV_FilePath = csv_path;
	}

	public void AddTitleFields(String fields) {
		data_records = fields + "\n";
	}

	public void AddElement(String element) {
		if (outputDevice == CSVFile)
			data_records = data_records + element + mySplitter;
		else
			System.out.print(element + " ");
	}

	public void NextLine() {
		if (outputDevice == CSVFile)
			data_records = data_records + "\n";
		else
			System.out.println("");
	}

	public void WriteAll() {
		if (outputDevice == CSVFile)
			try {
				// Create file
				FileWriter fstream = new FileWriter(CSV_FilePath);
				BufferedWriter out = new BufferedWriter(fstream);
				out.write(data_records);
				// Close the output stream
				out.close();
				System.out.println("CSV file is generated as " + CSV_FilePath);
			} catch (Exception e) {// Catch exception if any
				System.err.println("Error: " + e.getMessage());
			}
	}

	public String getNewCsvFP(String prefix) {

		DateTools ts = new DateTools();
		String csvFP = "C:\\Result-" + prefix + ts.getDateTime() + ".csv";
		File csvFile = new File(csvFP);

		int i = 1;
		while (csvFile.exists()) {
			csvFP = "C:\\Result-" + prefix + ts.getDateTime() + (i++) + ".csv";
			csvFile = new File(csvFP);
		}
		return csvFile.getPath();
	}

}
